package iceberg.readers;

import iceberg.domain.ArchitectureDefinition;
import iceberg.domain.StructureDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class XMLReader {

	private static final Logger LOG = LoggerFactory.getLogger(XMLReader.class);
	private final StructureDefinition definition;

	/**
	 * Reads the architecture definition and the structure definition files and based on those it builds
	 * a data-structure from that.
	 */
	public XMLReader() {
		ArchitectureDefinitionReader reader = new ArchitectureDefinitionReader();
		StructureDefinitionReader structureDefinitionReader = new StructureDefinitionReader();

		try {
			ArchitectureDefinition architectureDefinition = reader.read();
			structureDefinitionReader.setLayers(architectureDefinition.getLookupMap());
			structureDefinitionReader.setExceptions(architectureDefinition.getConstraintExceptions());
			definition = structureDefinitionReader.read();

		} catch (SAXException e) {
			LOG.error("The xml is corrupt", e);
			throw new IcebergException(e);
		} catch (IOException e) {
			LOG.error("Unable to read xml files", e);
			throw new IcebergException(e);
		} catch (ParserConfigurationException e) {
			LOG.error("The xml configuration is invalid", e);
			throw new IcebergException(e);
		}

		LOG.info(definition.toString());
	}

	public StructureDefinition getDefinition() {
		return definition;
	}

}
